<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>严格的上下文转义： $sce 服务</title>
    <link rel="stylesheet" href="../../lib/bootstrap3/css/bootstrap.min.css">
    <script src="../../lib/angularjs/angular1.6.3.min.js"></script>
</head>
<body ng-app="sceApp">
<div class="well">
    $sce是一个非常出色的服务，它允许我们编写白名单，默认保护代码，并在很大程度上帮助我们防止XSS和其他漏洞。
    <p>
        <b>要设置$sce保护，需要注入$sce服务。</b><br/>
        angular.module('myApp', [])<br/>
        .directive('myDirective', ['$sce', function($sce) {<br/>
        // 这里有权使用$sce服务<br/>
        }])<br/>
        .controller('MyController', ['$scope', '$sce', function($scope, $sce) {<br/>
        // 这里也有权使用$sce服务<br/>
        }]);<br/>
    </p>
</div>
<div class="well bg-success" ng-controller="ctrl01">

    <textarea ng-model="email.rawHtml"></textarea>
    <pre ng-bind-html="email.htmlBody"></pre>
</div>
<div class="well bg-success" ng-controller="ctrl02">
    <h2>假如还希望页面上能执行用户编写的自定义JavaScript会怎样呢？</h2>
    <p>
    $scope.a=function(){alert(11);}
        <div class="btn-danger btn" ng-click="a()">测试</div>
        <br/>
    </p>
    <textarea ng-model="email.rawJs"></textarea>
    <pre ng-bind="email.jsBody"></pre>
    <button ng-click="runJs()">Run</button>
</div>
</body>
<script>
    var app=angular.module("sceApp",[]);
    var ctrl01=app.controller("ctrl01",["$scope","$sce",function ($scope,$sce) {
        // 在email.rawHtml上设置监控
        $scope.$watch('email.rawHtml', function(v) {
            // 假设在非编译($compile)阶段
            if(v) {
                // 将htmlBody渲染为受信任的HTML
                $scope.email.htmlBody = $sce.trustAsHtml($scope.email.rawHtml);
            }
        });
    }]);
    var ctrl02=app.controller("ctrl02",["$scope","$sce",function ($scope,$sce) {
        // 在email.rawJs上设置监控
        $scope.$watch('email.rawJs', function(v) {
            if(v) {
                $scope.email.jsBody = $sce.trustAsJs($scope.email.rawJs);
            }
        });
        $scope.runJs = function() {
            eval($scope.email.jsBody.toString());
        };
    }]);
</script>
<style>
    textarea{width:100%;height:90px;resize: none;}
</style>
</html>